package com.example.demo.util;

import com.example.demo.model.Row;

import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * Created by huang on 2018/1/14.
 */
public class AppUtil {
    private void zip(String zipFileName, File inputFile) throws Exception {
        System.out.println("压缩中...");
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
                zipFileName));
        BufferedOutputStream bo = new BufferedOutputStream(out);
        zip(out, inputFile, inputFile.getName(), bo);
        bo.close();
        out.close(); // 输出流关闭
        System.out.println("压缩完成");
    }


    private void zip(ZipOutputStream out, File f, String base, BufferedOutputStream bo) throws Exception { // 方法重载
        int k =1;
        if (f.isDirectory()) {
            File[] fl = f.listFiles();
            if (fl.length == 0) {
                out.putNextEntry(new ZipEntry(base + "/")); // 创建zip压缩进入点base
                System.out.println(base + "/");
            }
            for (int i = 0; i < fl.length; i++) {
                zip(out, fl[i], base + "/" + fl[i].getName(), bo); // 递归遍历子文件夹
            }
            System.out.println("第" + k + "次递归");
            k++;
        } else {
            out.putNextEntry(new ZipEntry(base)); // 创建zip压缩进入点base
            System.out.println(base);
            FileInputStream in = new FileInputStream(f);
            BufferedInputStream bi = new BufferedInputStream(in);
            int b;
            while ((b = bi.read()) != -1) {
                bo.write(b); // 将字节流写入当前zip目录
            }
            bi.close();
            in.close(); // 输入流关闭
        }
    }
    public static void unzipIt(String zipFile,String destination) throws IOException {
        ZipFile zip=new ZipFile(zipFile);
        Enumeration en=zip.entries();
        ZipEntry entry=null;
        byte[] buffer=new byte[8192];
        int length=-1;
        InputStream input=null;
        BufferedOutputStream bos=null;
        File file=null;

        while(en.hasMoreElements()) {
            entry=(ZipEntry)en.nextElement();
            if(entry.isDirectory()) {
                System.out.println("directory");
                continue;
            }

            input=zip.getInputStream(entry);
            file=new File(destination,entry.getName());
            if(!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            bos=new BufferedOutputStream(new FileOutputStream(file));

            while(true) {
                length=input.read(buffer);
                if(length==-1) break;
                bos.write(buffer,0,length);
            }
            bos.close();
            input.close();
        }
        zip.close();
    }
    /**
     *
     * @Description: TODO(找到文件并读取解压到指定目录)
     * @param
     * @return void 返回类型
     * @throws
     */
    public static void unZipFile(ZipEntry ze, InputStream read, String saveRootDirectory) throws FileNotFoundException, IOException {
        // 如果只读取图片，自行判断就OK.
        long date = new Date().getTime();
        String time = date+"";
        String fileName= ze.getName();
        // 判断文件是否符合要求或者是指定的某一类型
//      if (fileName.equals("WebRoot/WEB-INF/web.xml")) {
        // 指定要解压出来的文件格式（这些格式可抽取放置在集合或String数组通过参数传递进来，方法更通用）
        File file = new File(saveRootDirectory + fileName);
        if (!file.exists()) {
            File rootDirectoryFile = new File(file.getParent());
            // 创建目录
            if (!rootDirectoryFile.exists()) {
                boolean ifSuccess = rootDirectoryFile.mkdirs();
                if (ifSuccess) {
                    System.out.println("文件夹创建成功!");
                } else {
                    System.out.println("文件创建失败!");
                }
            }
            // 创建文件
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 写入文件
        BufferedOutputStream write = new BufferedOutputStream(new FileOutputStream(file));
        int cha = 0;
        while ((cha = read.read()) != -1) {
            write.write(cha);
        }
        // 要注意IO流关闭的先后顺序
        write.flush();
        write.close();
        read.close();
        // }
//      }
    }
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }

    public static String listToString(List list){
        String rSting = "";
        if (list.size() == 0 || list == null){
            return "";
        }
        for (int j = 0; j < list.size(); j++) {
            String str =  list.get(j)+"";
            if (list.size()-1 == j){
                rSting+= str;
            }else{
                rSting+= str+",";
            }
        }
//        list.forEach(System.out::println);
        return rSting;
    }

    public static String listTwoToString(List<List<String>> list){

        String rSting = "";
        if (list.size() == 0 || list == null){
            return "";
        }
        for (int j = 0; j < list.size(); j++) {
            String str = listToString(list.get(j));
            if (list.size()-1 == j){
                rSting+= str;
            }else{
                rSting+= str+"&";
            }
        }
//        list.forEach(System.out::println);
        return rSting;
    }


    public static byte[] getBytes1(String filePath){
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            org.apache.commons.io.output.ByteArrayOutputStream bos = new org.apache.commons.io.output.ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    public static List<Row> matrixToRow(List<List<String>> lls){
        List<Row> rows = new ArrayList<>();
        for(List<String> l : lls){
            Row row = new Row();
            row.setColumns(l);
            rows.add(row);
        }
        return rows;
    }

    public static TreeSet<Row> matrixToSet(List<List<String>> lls){
        TreeSet<Row> rows = new TreeSet<>();
        for(List<String> l : lls){
            Row row = new Row();
            row.setColumns(l);
            rows.add(row);
        }
        return rows;
    }

    public static List<List<String>> rowSetToMatrix(Set<Row> secretCommittee) {
        Iterator iter = secretCommittee.iterator();
        List<List<String>> list = new ArrayList<>();
        while (iter.hasNext()){
            Row row = (Row) iter.next();
            list.add(row.getColumns());
        }
        return list;
    }

    public static List<List<String>> rowToMatrix(List<Row> secretCommittee) {
        Iterator iter = secretCommittee.iterator();
        List<List<String>> list = new ArrayList<>();
        while (iter.hasNext()){
            Row row = (Row) iter.next();
            list.add(row.getColumns());
        }
        return list;
    }
}
